import React, { Component } from 'react';
import { Tabs, message, Spin } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import styles from './index.less';
import LineChart from '../LineChart/index';

const { TabPane } = Tabs;
/**
 * 财务分析Tab切换图表
 */

class TabsChart extends Component {
  static propTypes = {
    charts: PropTypes.array,
    descs: PropTypes.object,
    curTabKey: PropTypes.string,
    curDesc: PropTypes.string,
  };

  static defaultProps = {
    charts: [],
    descs: {},
    curTabKey: 0,
    curDesc: '',
  };

  componentDidUpdate(prevProps, prevState) {
    if (prevProps.charts.length !== this.props.charts.length) {
      const { curTabKey } = this.props;
      this.drawChart(curTabKey);
    }
  }

  drawChart(key) {
    const { dispatch, tabs, charts, descs } = this.props;
    const chartName = tabs[key].tab;
    let fd = {};
    let desc = '';
    if (charts.length === 0) {
      // message.error('暂无数据');
      console.log('暂无数据');
      return;
    }
    const fds = charts.filter(item => {
      return item.name === chartName;
    });
    if (fds.length === 0) {
      // message.error('暂无数据');]
      console.log('暂无数据');
      return;
    }
    fd = fds[0];
    desc = descs['x' + (+key + 1)];

    // 设置当前描述和渲染图表
    dispatch({
      type: 'finance/renderChart',
      payload: {
        chartID: `lineChart${chartName}`,
        fd,
        desc,
      },
    });
  }

  onChange = key => {
    console.log(key, typeof key);
    this.drawChart(key);
  };

  render() {
    const { tabs, desc, curTabKey, isLoading, curDesc } = this.props;
    return (
      <div className={styles.payDebt}>
        <Tabs type="card" defaultActiveKey={curTabKey} tabPosition="left" onChange={this.onChange}>
          {tabs.map(item => (
            <TabPane tab={item.tab} key={item.key} forceRender>
              <Spin spinning={false} style={{ width: '100%' }}>
                <LineChart
                  curDesc={curDesc}
                  chartIndex={item.key}
                  itemName={item.tab}
                  chartID={`lineChart${item.tab}`}
                  title={item.tab}
                />
              </Spin>
            </TabPane>
          ))}
        </Tabs>
      </div>
    );
  }
}

const mapStateToProps = ({ finance, loading }) => ({
  descs: finance.descs,
  charts: finance.charts,
  curTabKey: finance.curTabKey,
  curDesc: finance.curDesc,
  //isLoading: loading.effects['finance/getCharts'],
});
export default connect(mapStateToProps)(TabsChart);
